const { Application } = require('../models');
const { Op } = require('sequelize');
const logger = require('../utils/logger');

class ApplicationService {
  /**
   * 创建应用
   * @param {Object} data - 应用数据
   * @returns {Promise<Application>} - 创建的应用
   */
  async createApplication(data) {
    try {
      const application = await Application.create(data);
      logger.info(`应用创建成功，ID: ${application.id}`);
      return application;
    } catch (error) {
      logger.error('创建应用时出错:', error);
      throw error;
    }
  }

  /**
   * 获取应用列表
   * @param {Object} filters - 过滤条件
   * @returns {Promise<Array<Application>>} - 应用列表
   */
  async getApplications(filters = {}) {
    try {
      const where = {};
      if (filters.status) {
        where.status = filters.status;
      }
      if (filters.type) {
        where.type = filters.type;
      }
      if (filters.search) {
        where[Op.or] = [
          { name: { [Op.like]: `%${filters.search}%` } },
          { description: { [Op.like]: `%${filters.search}%` } }
        ];
      }

      const applications = await Application.findAll({ where });
      return applications;
    } catch (error) {
      logger.error('获取应用列表时出错:', error);
      throw error;
    }
  }

  /**
   * 获取应用详情
   * @param {number} id - 应用ID
   * @returns {Promise<Application>} - 应用详情
   */
  async getApplicationById(id) {
    try {
      const application = await Application.findByPk(id);
      if (!application) {
        throw new Error('未找到应用');
      }
      return application;
    } catch (error) {
      logger.error(`获取应用 ID ${id} 时出错:`, error);
      throw error;
    }
  }

  /**
   * 更新应用
   * @param {number} id - 应用ID
   * @param {Object} data - 更新数据
   * @returns {Promise<Application>} - 更新后的应用
   */
  async updateApplication(id, data) {
    try {
      const application = await this.getApplicationById(id);
      await application.update(data);
      logger.info(`应用 ${id} 更新成功`);
      return application;
    } catch (error) {
      logger.error(`更新应用 ${id} 时出错:`, error);
      throw error;
    }
  }

  /**
   * 删除应用
   * @param {number} id - 应用ID
   * @returns {Promise<boolean>} - 删除结果
   */
  async deleteApplication(id) {
    try {
      const application = await this.getApplicationById(id);
      await application.destroy();
      logger.info(`应用 ${id} 删除成功`);
      return true;
    } catch (error) {
      logger.error(`删除应用 ${id} 时出错:`, error);
      throw error;
    }
  }

  /**
   * 更新应用状态
   * @param {number} id - 应用ID
   * @param {string} status - 新状态
   * @returns {Promise<Application>} - 更新后的应用
   */
  async updateApplicationStatus(id, status) {
    try {
      const application = await this.getApplicationById(id);
      await application.update({ status });
      logger.info(`应用 ${id} 状态更新为 ${status}`);
      return application;
    } catch (error) {
      logger.error(`更新应用 ${id} 状态时出错:`, error);
      throw error;
    }
  }

  /**
   * 获取应用统计信息
   * @param {number} id - 应用ID
   * @returns {Promise<Object>} - 应用统计信息
   */
  async getApplicationStats(id) {
    try {
      const application = await this.getApplicationById(id);
      // Implement application statistics gathering logic here
      const stats = {
        totalUsers: await application.countUsers(),
        activeUsers: 0, // Implement active users count
        lastAccessed: application.lastAccessedAt,
        apiCalls: application.apiCallCount || 0,
        errorRate: application.errorRate || 0
      };
      return stats;
    } catch (error) {
      logger.error(`获取应用 ${id} 统计信息时出错:`, error);
      throw error;
    }
  }

  /**
   * 验证应用访问权限
   * @param {number} id - 应用ID
   * @param {number} userId - 用户ID
   * @returns {Promise<boolean>} - 是否有权限
   */
  async validateApplicationAccess(id, userId) {
    try {
      const application = await this.getApplicationById(id);
      const hasAccess = await application.hasUser(userId);
      return hasAccess;
    } catch (error) {
      logger.error(`验证应用 ${id} 用户 ${userId} 访问权限时出错:`, error);
      throw error;
    }
  }

  /**
   * 分配用户到应用
   * @param {number} id - 应用ID
   * @param {number} userId - 用户ID
   * @param {string} role - 角色
   * @returns {Promise<boolean>} - 分配结果
   */
  async assignUserToApplication(id, userId, role = 'user') {
    try {
      const application = await this.getApplicationById(id);
      await application.addUser(userId, { through: { role } });
      logger.info(`用户 ${userId} 已分配到应用 ${id}，角色为 ${role}`);
      return true;
    } catch (error) {
      logger.error(`分配用户 ${userId} 到应用 ${id} 时出错:`, error);
      throw error;
    }
  }

  /**
   * 从应用中移除用户
   * @param {number} id - 应用ID
   * @param {number} userId - 用户ID
   * @returns {Promise<boolean>} - 移除结果
   */
  async removeUserFromApplication(id, userId) {
    try {
      const application = await this.getApplicationById(id);
      await application.removeUser(userId);
      logger.info(`用户 ${userId} 已从应用 ${id} 中移除`);
      return true;
    } catch (error) {
      logger.error(`从应用 ${id} 移除用户 ${userId} 时出错:`, error);
      throw error;
    }
  }

  /**
   * 更新应用配置
   * @param {number} id - 应用ID
   * @param {Object} config - 新配置
   * @returns {Promise<Application>} - 更新后的应用
   */
  async updateApplicationConfig(id, config) {
    try {
      const application = await this.getApplicationById(id);
      await application.update({ config });
      logger.info(`应用 ${id} 配置更新成功`);
      return application;
    } catch (error) {
      logger.error(`更新应用 ${id} 配置时出错:`, error);
      throw error;
    }
  }
}

module.exports = new ApplicationService(); 